import { ref } from 'vue'
const isValidJWT = (token) => {
    if (typeof token !== 'string') return false
    try {
        const [header, payload, signature] = token.split('.')
        return Boolean(
            header && payload && signature &&
            JSON.parse(atob(header)) &&
            JSON.parse(atob(payload))
        )
    } catch (e) {
        return false
    }
}
export const token = ref(localStorage.getItem('access_token'))
export const refreshToken = ref(localStorage.getItem('refresh_token'))
export const isLoggedIn = ref(localStorage.getItem('isLoggedIn') === 'true')
export const userInfo = ref(JSON.parse(localStorage.getItem('user_info') || '{}'))
const shouldRefreshUserInfo = () => {
    const lastUpdate = localStorage.getItem('user_info_last_update')
    return !lastUpdate || Date.now() - parseInt(lastUpdate) > 300000 // 5分钟
}
export const authHandler={
    setAuthInfo(...args) {
        // 方式一：传入access, refresh, userData
        if (typeof args[0] === 'string' && typeof args[1] === 'string') {
            const [access, refresh, userData] = args
            // 新增校验逻辑
            if (!isValidJWT(access) || !isValidJWT(refresh)) {
                this.clearAuthInfo()
                throw new Error('无效的令牌格式')
            }
            token.value = access
            refreshToken.value = refresh
            isLoggedIn.value = true

            // 存储认证信息
            localStorage.setItem('access_token', access)
            localStorage.setItem('refresh_token', refresh)
            localStorage.setItem('isLoggedIn', 'true')
            localStorage.setItem('token_expire',Date.now() + 86400 * 1000)

            // 可选存储用户信息
            if (userData) {
                userInfo.value = userData
                localStorage.setItem('user_info', JSON.stringify(userData))
            }
        }
        // 方式二：只传入userInfo
        else if (typeof args[0] === 'object') {
            const [userData] = args
            userInfo.value = userData
            localStorage.setItem('user_info', JSON.stringify(userData))
        }
    },
    
getUserInfo() {
    
if (!token.value) return null;
if (!shouldRefreshUserInfo()) {
        return JSON.parse(localStorage.getItem('user_info') || '{}')
    }
try {
    userInfo.value = JSON.parse(localStorage.getItem('user_info') || '{}')
    return userInfo.value
} catch (error) {
    console.error('获取用户信息失败:', error)
    return null
}
},
clearAuthInfo() {
    token.value = null
    refreshToken.value = null
    isLoggedIn.value = false
    userInfo.value = {}
    //cookie也要清除
    document.cookie = 'reset_token=;path=/;'
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('user_info')
    localStorage.removeItem('token_expire')
    localStorage.removeItem('user_avatar')
},

checkAuth() {
    const tokenExpire = localStorage.getItem('token_expire')
    if (!token.value || !tokenExpire) return false
    return Date.now() < parseInt(tokenExpire)
}
}

 